package interceptor;

import constant.ExamConstant;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

@WebFilter(filterName = "checkLogin" , urlPatterns = {"/*"},
        initParams = {@WebInitParam(name="noCheck",value="/login,/login.jsp,/registerDoctor.jsp," +
                "/registerDoctor,/registerPatient.jsp,/registerPatient,.js,.css,.jpg,.png")})
public class LoginInterceptor implements Filter {
    private  String[] noCheckList;

    private boolean doCheck(String uri,String rootPath) {
        boolean doCheckFlag = true;
        if (uri.equals(rootPath + "/")) {
            return false;
        }else {
            for (String item : noCheckList){
                if (uri.endsWith(item)){
                    doCheckFlag = false;
                    break;
                }
            }
        }
        return doCheckFlag;
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException{
        String noCheckStr = filterConfig.getInitParameter("noCheck");
        this.noCheckList = noCheckStr.split(",");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
            throws IOException, ServletException {
        Object type = ((HttpServletRequest) request).getSession().getAttribute(ExamConstant.SESSION_LOGIN_TYPE);
        String rootPath = ((HttpServletRequest) request).getContextPath();
        String uri = ((HttpServletRequest) request).getRequestURI();
        if(doCheck(uri,rootPath) && !ExamConstant.LOGIN_TYPE_DOCTOR.equals(type)
                && !ExamConstant.LOGIN_TYPE_PATIENT.equals(type)){
            request.setAttribute("error","请先进行登陆");
            request.getRequestDispatcher(ExamConstant.HOME_PAGE_LOGIN).forward(request,response);
        }else {
            filterChain.doFilter(request,response);
        }
    }

    @Override
    public void destroy() {

    }
}
